package com.yupi.springbootinit.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import org.junit.jupiter.api.Test;

import java.util.Scanner;

/**
 * @Description
 * @Author minify
 * @Date 2023/12/17 23:33
 * @Project mybi-backend
 */
public class ProductMulti {

    private final static String QUEUE_NAME_MUTI = "hello_muti";
    /**
     * 消息生产者1对多
     */
    public static void main(String[] args) throws Exception {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置RabbitMQ相关信息
        factory.setHost("localhost");
        // 创建一个新的连接
        Connection connection = factory.newConnection();
        // 创建一个通道
        Channel channel = connection.createChannel();

        // 声明要关注的队列
        // 队列持久化
        channel.queueDeclare(QUEUE_NAME_MUTI, true, false, false, null);

        Scanner scanner = new Scanner(System.in);
        System.out.println("Producer1 Waiting for messages");
        while (scanner.hasNext()) {
            // 发送消息到队列中
            String message = scanner.nextLine();
            // 消息持久化
            channel.basicPublish("", QUEUE_NAME_MUTI, MessageProperties.MINIMAL_PERSISTENT_BASIC, message.getBytes("UTF-8"));
            System.out.println("Producer Send +'" + message + "'");
        }

        // 关闭通道和连接
        channel.close();
        connection.close();
    }
}
